#= require common/app

## package login

window.login = {}

## private

#TODO: Change so this can be more easily updated with new languages
get_language = (code) ->
  switch code
    when "jp" then return "Japanese"
    else return code

try_login = ->
  return if $('#username-box').val() is '' or $('#password-box').val() is ''
  console.log "Sending: #{$('#username-box').val()}, #{hash($('#password-box').val())}"
  $.post '/users/validate', { u: $('#username-box').val(), p: hash($('#password-box').val()) }, (data) ->
    if data.app?
      login_app data
    else if data.control?
      login_control data
    else
      login_fail data

login_app = (data) ->
  $.get '/app/get', (html) ->
    $('body').html html
    initialize_app data

initialize_app = (data) ->
  initialize()
  $('#user-display').text data.rn
  if not data.uc
    0 #TODO: Show 'add class' dialog
  else if typeof data.uc == 'array'
    0 #TODO: Show class picker
  else
    load_class uc
  $('#login-box').modal 'hide'
  $('.navbar').fadeIn()
  $('#dojo').fadeIn()
  
login_control = (data) ->
  $.get '/school/control/get', (html) ->
    $('body').html html
    initialize_control data

initialize_control = (data) ->
  initialize data
  
login_fail = ->
  $.meow { message: "Username or password not valid!" }
  $('#login-btn').button 'reset'

load_class = (uc) ->
  login.language = uc.la
  login.class = uc.cl
  login.language_name = get_language uc.la
  $.post '/data/get', { l: uc.la, c: uc.cl }, (data) ->
    vocab.load data.v
    grammar.load data.g
    activities.load data.a
    $('.lang-img').hide()
    $("##{uc.la}-img").show()

## public

## initialize

$ ->
  $('#login-box').modal { backdrop: off, keyboard: off }
  $('#login-btn').click ->
    $('#login-btn').button 'loading'
    try_login()
